package ipad.asia.config;

import ipad.asia.utils.MD5Util;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.boot.SpringApplication;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

@Component
public class FtpEnterprise {


    /**
     * 直接下载所有的文件到upload文件，不用每次加载文件。
     * 如果后期有文件服务器，会使用fastdfs配合nginx
     * @return
     * @throws IOException
     */
    public static boolean downloadFile() throws IOException {
        String host = "172.81.238.137";
        int port = 21;
        String username = "feng";
        String password = "6369180fdw";
        String basePath = "upload";
        String remotePath = "upload/shop";
        File path=new File("consumer-enterprise-6001/src/main/resources");
        System.out.println(path.getCanonicalPath());
        String localPath= path.getAbsolutePath() +"/upload";
        System.out.println(localPath);
        boolean result = false;
        FTPClient ftp = new FTPClient();
        ftp.setAutodetectUTF8(true);
        try {
            int reply;
            ftp.connect(host, port);
            // 如果采用默认端口，可以使用ftp.connect(host)的方式直接连接FTP服务器
            ftp.login(username, password);// 登录
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return result;
            }

            ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
            FTPFile[] fs = ftp.listFiles();
            for (FTPFile ff : fs) {
                System.out.println("========="+ff.getName());
                //if (ff.getName().equals(fileName)) {
                File localFile = new File(localPath + "/" + ff.getName());
                if(!localFile.exists())
                {
                    System.out.println("文件不存在");
                    OutputStream is = new FileOutputStream(localFile);
                    ftp.retrieveFile(ff.getName(), is);
                    is.close();
                }else{
                    System.out.println("文件存在");
                }
                //}
            }


            ftp.logout();
            result = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return result;
    }
}
